'use client';

import { useEffect, useState } from 'react';
import { useRouter, usePathname } from 'next/navigation';

interface AuthGuardProps {
  children: React.ReactNode;
}

const AuthGuard: React.FC<AuthGuardProps> = ({ children }) => {
  const router = useRouter();
  const pathname = usePathname();
  const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(null);

  // 不需要认证的页面
  const publicRoutes = ['/login', '/register', '/email-login'];

  useEffect(() => {
    const checkAuth = () => {
      const token = localStorage.getItem('userToken');
      
      if (token) {
        setIsAuthenticated(true);
      } else {
        setIsAuthenticated(false);
        // 如果当前页面不是公开页面，重定向到登录页
        if (!publicRoutes.includes(pathname)) {
          router.push('/login');
        }
      }
    };

    checkAuth();
  }, [pathname, router]);

  // 如果是公开页面，直接渲染
  if (publicRoutes.includes(pathname)) {
    return <>{children}</>;
  }

  // 如果还在检查认证状态，显示加载
  if (isAuthenticated === null) {
    return (
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh',
        background: 'linear-gradient(135deg, rgba(74, 144, 226, 0.8) 0%, rgba(80, 170, 255, 0.6) 100%)',
        color: 'white',
        fontSize: '18px'
      }}>
        正在验证身份...
      </div>
    );
  }

  // 如果已认证，渲染子组件
  if (isAuthenticated) {
    return <>{children}</>;
  }

  // 如果未认证，不渲染任何内容（会重定向到登录页）
  return null;
};

export default AuthGuard;